import 'package:flutter/material.dart';

// 创建一个计时器的示例：每隔1秒，计数加1。
class StreamBuilderPage extends StatefulWidget {
  @override
  _StreamBuilderPageState createState() => _StreamBuilderPageState();
}

class _StreamBuilderPageState extends State<StreamBuilderPage> {
  final Duration _interval = Duration(seconds: 1); // 自定义间隔时间
  final int _initialValue = 0; // 自定义初始值

  Stream<int> counter() {
    return Stream.periodic(_interval, (i) {
      return _initialValue + i;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('StreamBuilder Demo')),
      body: Center(
        child: StreamBuilder<int>(
          stream: counter(),
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('Error: ${snapshot.error}'),
                  ElevatedButton(
                    onPressed: () {
                      setState(() {});
                    },
                    child: Text('重试'),
                  ),
                ],
              );
            }
            switch (snapshot.connectionState) {
              case ConnectionState.none:
                return Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text('没有Stream'),
                    ElevatedButton(
                      onPressed: () {
                        setState(() {});
                      },
                      child: Text('开始Stream'),
                    ),
                  ],
                );
              case ConnectionState.waiting:
                return CircularProgressIndicator();
              case ConnectionState.active:
                return Text('计数: ${snapshot.data}');
              case ConnectionState.done:
                return Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text('Stream 已关闭'),
                    ElevatedButton(
                      onPressed: () {
                        setState(() {});
                      },
                      child: Text('重新开始Stream'),
                    ),
                  ],
                );
            }
          },
        ),
      ),
    );
  }
}
